// userPageC/pages/userPersonal/order/order.js
const app = getApp()
const WXAPI = require("../../../../api/api")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 1, // 是否显示左上角图标   1表示显示    0表示不显示
      title: '订单中心', // 导航栏 中间的标题
      textColor: '#000', // 标题颜色
      bgColor: '#fff', // 导航栏背景颜色
      isloading: true,
      isColor: true,
    },
    navList: [{
        id: 0,
        value: '全部'
      },
      {
        id: 1,
        value: '待支付'
      },
      {
        id: 2,
        value: '已完成'
      },
      {
        id: 3,
        value: '待评价'
      },
      {
        id: 4,
        value: '已取消'
      },
    ],
    currentNavtab: 0,
    likeKey: '',
    payStatus: '', //状态
    evaluateStatus: '', //评价状态 1-已评价 2-待评价
    orderTypeStatus: '', //订单类型 1-扫码支付 2-购卡 3-用卡
    pageSize: 10,
    pageNum: 1,
    cardTotal: 0,
    orderList: [],
    loadingType: 0, //加载状态（0：加载中  1：加载完成没有更多）
    isPull: true, //是否刷新
    imgHttp: app.globalData.imgHttp, //图片前缀
    orderId: '',
    orderType: '', //订单类型
    orderTypeStatusLs:[
      {id:2,value:'购卡'},{id:3,value:'用卡'},{id:1,value:'扫码支付'}
    ],
    changeIndex: 99,
    propShow: false,//订单筛选弹窗
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let index = options.index
    if (index == 0) { //待支付
      this.data.currentNavtab = 1
      this.data.payStatus = 1
      this.data.evaluateStatus = ''
    } else if (index == 1) { //已完成
      this.data.currentNavtab = 2
      this.data.payStatus = 2
      this.data.evaluateStatus = ''
    } else if (index == 2) { //待评价
      this.data.currentNavtab = 3
      this.data.payStatus = 2
      this.data.evaluateStatus = 2
    } else if (index == 3) { //全部
      this.data.currentNavtab = 0
      this.data.payStatus = ''
      this.data.evaluateStatus = ''
    }
    this.setData({
      currentNavtab: this.data.currentNavtab
    })
    this.getList()
  },
  // 我的评价
  jumpEvaluate(){
    wx.navigateTo({
      url: '/userPageB/pages/evaluationList/evaluationList?merchantId=' + '' + '&queryCustomer=' + 1,
    })
  },
  //筛选弹窗打开
  propShowClick(){
    console.log(2121)
    this.setData({
      propShow: true
    })
    console.log(this.data.propShow)
  },
  //筛选弹窗关闭
  propShowClose(){
    this.setData({
      propShow: false,
      changeIndex: 99
    })
  },
  // 订单筛选
  propChoice(e){
    let id = e.currentTarget.dataset.id
    let index = e.currentTarget.dataset.index
    this.data.orderTypeStatus = id
    this.setData({
      changeIndex: index
    })
  },
  // 筛选重置
  resetClick(){
    this.data.orderTypeStatus = ''
    this.data.pageNum = 1
    this.getList()
    this.setData({
      changeIndex: 99,
      propShow: false,
    })
  },
  // 筛选确认
  confirmClick(){
    this.data.pageNum = 1
    this.getList()
    this.setData({
      propShow: false,
    })
  },
  //订单列表
  getList() {
    var data = {
      likeKey: this.data.likeKey,
      payStatus: this.data.payStatus,
      evaluateStatus: this.data.evaluateStatus,
      orderType: this.data.orderTypeStatus,
      pageSize: this.data.pageSize,
      pageNum: this.data.pageNum,
    }
    WXAPI.getOrderList(data, (res) => {
      const data = res.result
      if (res.code === 200) {
        // const {
        //   size,
        //   total,
        //   records
        // } = res.result
        // var list = []
        // var orderList = this.data.orderList
        // if (this.data.pageNum >= Math.ceil(total / size)) {
        //   this.setData({
        //     lodingtype: 1,
        //     isPull: false,
        //   })
        // } else {
        //   this.setData({
        //     lodingtype: 0
        //   })
        // }
        // wx.hideLoading()
        // list = records
        // this.setData({
        //   orderList: orderList.concat(list),
        // })
        this.data.cardTotal = res.result.total
        if (this.data.pageNum >= Math.ceil(this.data.cardTotal / this.data.pageSize)) {
          this.setData({
            lodingtype: 1
          })
        } else {
          this.setData({
            lodingtype: 0
          })
        }

        if (this.data.pageNum > 1) {
          this.data.orderList = this.data.orderList.concat(res.result.records); //将数据拼接在一起
          this.setData({
            orderList: this.data.orderList
          })
        } else {
          this.data.orderList = res.result.records
          this.setData({
            orderList: this.data.orderList
          })
        }
        wx.hideLoading()
      }
    })
  },
  //切换订单类型
  handleCurrent(e) {
    var id = e.currentTarget.dataset.id
    if (id == 0) { //全部
      this.data.currentNavtab = 0
      this.data.payStatus = ''
      this.data.evaluateStatus = ''
    } else if (id == 1) { //待支付
      this.data.currentNavtab = 1
      this.data.payStatus = 1
      this.data.evaluateStatus = ''
    } else if (id == 2) { //已完成
      this.data.currentNavtab = 2
      this.data.payStatus = 2
      this.data.evaluateStatus = ''
    } else if (id == 3) { //待评价
      this.data.currentNavtab = 3
      this.data.payStatus = 2
      this.data.evaluateStatus = 2
    } else { //已取消
      this.data.currentNavtab = 4
      this.data.payStatus = 3
      this.data.evaluateStatus = ''
    }
    this.setData({
      currentNavtab: this.data.currentNavtab,
      pageNum: 1,
      loadingType: 0,
    })
    this.getList()
  },
  //搜索订单
  handleInp(e) {
    var name = e.detail.value
    if (name) {
      this.setData({
        likeKey: name,
        currentNavtab: '',
        pageNum: 1,
        orderList: [],
      })
    } else {
      this.setData({
        likeKey: '',
        currentNavtab: '',
        pageNum: 1,
        orderList: [],
      })
    }
    this.getList()
  },
  handleDetail(e) {
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/userPageC/pages/userPersonal/order/orderDetail/orderDetail?orderId=' + id,
    })
  },
  // 跳转商家
  jumpShop(e){
    var shopId = e.currentTarget.dataset.shopid
    wx.navigateTo({
      url: '/userPageB/pages/userStore/storesDetails/storesDetails?shopId=' + shopId,
    })
  },
  //取消订单
  cancelOrder(e) {
    var that = this
    var id = e.currentTarget.dataset.id
    wx.showModal({
      title: '是否取消订单',
      cancelText: '取消',
      confirmColor: '#FF5800',
      confirmText: '确定',
      success(res) {
        if (res.confirm) {
          var data = {
            id: id
          }
          WXAPI.cancelOrder(data, (res) => {
            const data = res.result
            if (res.code === 200) {
              console.log('取消订单', res)
              that.setData({
                pageNum: 1,
                orderList: [],
              })
              that.getList()
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  //删除订单
  deleteOrder(e) {
    var that = this
    var id = e.currentTarget.dataset.id
    wx.showModal({
      title: '是否删除订单',
      cancelText: '取消',
      confirmColor: '#FF5800',
      confirmText: '确定',
      success(res) {
        if (res.confirm) {
          var data = {
            id: id
          }
          WXAPI.deleteOrder(data, (res) => {
            const data = res.result
            if (res.code === 200) {
              console.log('删除订单', res)
              that.setData({
                pageNum: 1,
                orderList: [],
              })
              that.getList()
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //评价
  evaluation(e) {
    var orderId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/userPageC/pages/userPersonal/evaluate/evaluate?orderId=' + orderId,
    })
  },
  //支付订单
  payOrder(e) {
    var id = e.currentTarget.dataset.id
    var orderType = e.currentTarget.dataset.type
    this.setData({
      orderType: orderType
    })
    var data = {
      id: id
    }
    WXAPI.payOrder(data, (res) => {
      const data = res.result
      if (res.code === 200) {
        console.log('支付订单', res)
        this.setData({
          orderId: data.orderId
        })
        this.wxpay(data)
      }
    })
  },
  //拉起微信支付
  wxpay(data) {
    var that = this
    console.log('data', data)
    wx.requestPayment({
      'timeStamp': data.timeStamp,
      'nonceStr': data.nonceStr,
      'package': data.package,
      'signType': data.signType, //MD5
      'paySign': data.paySign,
      'success': function (res) {
        console.log('支付成功', res)
        console.log(res)
        if (res.errMsg == 'requestPayment:ok') {
          // wx.showToast({
          //   title: '支付成功',
          //   icon: 'success',
          //   duration: 1200
          // })
          // that.setData({
          //   pageNum: 1,
          //   orderList: [],
          // })
          // that.getList()
          that.getCardPayorder()

        }
      },
      'fail': function (res) {
        wx.showToast({
          title: '支付失败',
          icon: 'none'
        })
        console.log('支付失败或取消支付', res)
      },
      'complete': function (res) {
        console.log('支付完成', res)
        // wx.navigateBack({})
      }
    })
  },
  //购卡订单支付结果
  getCardPayorder() {
    const that = this
    var orderType = this.data.orderType
    this.setData({
      timer: setInterval(function () { //这里把setInterval赋值给变量名为timer的变量
        that.data.countdown--;
        var data = {
          orderId: that.data.orderId,
        }
        if (orderType == 1) { //扫码支付获取结果
          WXAPI.payResult(data, (res) => {
            const data = res.result
            console.log("获取支付结果", data.isPay)
            if (data.isPay) {
              wx.redirectTo({
                url: '/pages/pay/paySuccess/paySuccess?orderId=' + that.data.orderId + '&anonymity=' + that.data.anonymity,
              })
              clearInterval(that.data.timer);
            }
          })
        } else if (orderType == 2 || orderType == 7) { //购卡支付获取结果
          WXAPI.getBuyCardPayResult(data, (res) => {
            const data = res.result
            console.log("获取支付结果", res)
            if (data.isPay) {
              wx.redirectTo({
                url: '/userPageB/pages/userStore/resellScuuess/resellScuuess?orderId=' + that.data.orderId + "&pathType=cardPay",
              })
              clearInterval(that.data.timer);
            }
          })
        } else if (orderType == 3) { //转卖购卡支付获取结果
          WXAPI.getResellPayResult(data, (res) => {
            const data = res.result
            console.log("获取支付结果", res)
            if (data.isPay) {
              wx.redirectTo({
                url: '/userPageB/pages/userStore/resellScuuess_one/resellScuuess_one?assetType=' + data.assetType + "&assetId=" + data.assetId + '&cardType=' + data.cardType + 'cardId=' + data.customerCardId,
              })
              clearInterval(that.data.timer);
            }
          })
        } else if (orderType == 4) { //充值支付获取结果
          WXAPI.getRechargePayResult(data, (res) => {
            const data = res.result
            console.log("获取支付结果", res)
            if (data.isPay) {
              wx.redirectTo({
                url: '/userPageA/pages/topupSuccess/topupSuccess?orderId=' + that.data.orderId,
              })
              clearInterval(that.data.timer);
            }
          })
        }
        that.setData({
          countdown: that.data.countdown,
        })
        if (that.data.countdown == 0) {
          console.log("1111111111")
          clearInterval(that.data.timer);
          that.setData({
            countdown: 60,
          })
        }
      }, 1000)
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // if (this.data.isPull == true) {
    //   var pageNum = this.data.pageNum
    //   pageNum++
    //   console.log("触底了", pageNum)
    //   this.setData({
    //     pageNum: pageNum
    //   });
    //   this.getList()
    // }
    console.log("触底了", this.data.pageNum, Math.ceil(this.data.cardTotal / this.data.pageSize), this.data.cardTotal)
    if (this.data.pageNum >= Math.ceil(this.data.cardTotal / this.data.pageSize)) {
      console.log('没有分页')
      this.setData({
        lodingtype: 1
      })
    } else {
      this.setData({
        lodingtype: 0
      })
      this.data.pageNum++; //每触底一次 page + 1;
      this.getList();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})